﻿using MongoDB.Driver.Core.Clusters.ServerSelectors;
using Prism.Commands;
using Prism.Dialogs;
using Prism.Mvvm;
using Prism.Navigation.Regions;
using Rafy.Domain;
using SwaggerSdk;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Windows.Input;

namespace Rafy.Book.ViewModels
{
    public class ZiciPageViewModel : BindableBase, INavigationAware
    {
        
        private readonly IDialogService _dialogService;

        private List<BookWordModel> AllWords =new List<BookWordModel>();
        
        private List<Base_CatalogBook> _catalogs;
        public List<Base_CatalogBook> Catalogs
        {
            get => _catalogs;
            set => SetProperty(ref _catalogs, value);
        }

        private Base_CatalogBook _selectedCatalog;
        public Base_CatalogBook SelectedCatalog
        {
            get => _selectedCatalog;
            set
            {
                if (_selectedCatalog != value)
                {
                    _selectedCatalog = value;

                    if (_selectedCatalog != null && _selectedCatalog.F_Cls == 10)
                    {
                        Console.WriteLine($"加载{_selectedCatalog.F_BooksId}={_selectedCatalog.Id}");
                        LoadWord(_selectedCatalog.F_BooksId, _selectedCatalog.Id);
                        LoadWords(_selectedCatalog.F_BooksId, _selectedCatalog.Id);
                    }
                }
            }
        }

        /// <summary>
        /// 内部字段，不在 IsAllWordsChecked 的 setter 中同步子项状态,做为标识
        /// </summary>
        private bool _isCheckingSingleWord = false;


        private bool _isAllWordsChecked;
        /// <summary>
        ///选择全部一个汉字
        /// </summary>
        public bool IsAllWordsChecked
        {
            get => _isAllWordsChecked;
            //set => SetProperty(ref _isAllWordsChecked, value);
            set
            {
                if (SetProperty(ref _isAllWordsChecked, value))
                {
                    Console.WriteLine($"全选/取消={_isCheckingSingleWord}");
                    // 只有用户点了全选/取消全选才设置子项
                    if (!_isCheckingSingleWord)
                    {
                        foreach (var item in SingleWords)
                        {
                            //Console.WriteLine($"{item.Character}={item.IsSelected}");
                            item.IsSelected = value;

                            //var match = AllWords.FirstOrDefault(w => w.Character == item.Character && w.CatalogId == item.CatalogId);
                            //Console.WriteLine($"{item.Character}={item.IsSelected}=={match.IsSelected}");
                            //if (match != null)
                            //{
                            //    match.IsSelected = value;
                            //}
                        }
                       
                        //最后更新章节右上标
                        int catid = SingleWords[0].CatalogId;//获取当前所在章节
                        var cats = Catalogs.FirstOrDefault(s => s.Id == catid);
                        if (cats != null)
                        {
                            cats.F_Count = AllWords.Where(s => s.CatalogId == catid && s.IsSelected == true).Count();
                        }
                        
                    }
                    Console.WriteLine($"*********AllWord={AllWords.Count},选中数={AllWords.Where(s => s.IsSelected).Count()}");
                }
            }
        }


        private bool _isCheckingPhrase = false;
        // 属性
        private bool _isAllPhraseChecked;
        /// <summary>
        /// 选择全部词语
        /// </summary>
        public bool IsAllPhraseChecked
        {
            get => _isAllPhraseChecked;
            set
            {
                if (SetProperty(ref _isAllPhraseChecked, value))
                {
                    //Console.WriteLine($"全选/取消={_isCheckingPhrase}");
                    if (!_isCheckingPhrase)
                    {
                        foreach (var item in Phrases)
                        {
                            
                            item.IsSelected = value;
                            //var match = AllWords.FirstOrDefault(w => w.Character == item.Character && w.CatalogId == item.CatalogId);
                            ////Console.WriteLine($"{item.Character}={item.IsSelected}=={match.IsSelected}");
                            //if (match != null)
                            //{
                            //    match.IsSelected = value;
                            //}
                        }
                        //最后更新章节右上标
                        int catid = Phrases[0].CatalogId;//获取当前所在章节
                        var cats = Catalogs.FirstOrDefault(s => s.Id == catid);
                        if (cats != null)
                        {
                            cats.F_Count = AllWords.Where(s => s.CatalogId == catid && s.IsSelected == true).Count();
                        }
                        
                    }
                    //Console.WriteLine($"&&&&&&&&&&&&&AllWord={AllWords.Count},选中数={AllWords.Where(s => s.IsSelected).Count()}");

                }
            }
        }

        private ObservableCollection<BookWordModel> _singleWords;
        public ObservableCollection<BookWordModel> SingleWords
        {
            get => _singleWords;
            set => SetProperty(ref _singleWords, value);
        }

        private ObservableCollection<BookWordModel> _phrases;
        public ObservableCollection<BookWordModel> Phrases
        {
            get => _phrases;
            set => SetProperty(ref _phrases, value);
        }

        // 命令
        public DelegateCommand AddCommand { get; }
        /// <summary>
        /// 选择单个汉字
        /// </summary>
        public DelegateCommand<object> CharacterCommand { get; }
        public DelegateCommand CancelExerciseCommand { get; private set; }
        public DelegateCommand StartExerciseCommand { get; private set; }
        /// <summary>
        /// 打印已选择词语
        /// </summary>
        public DelegateCommand PrintCommand {  get; private set; }
        public ZiciPageViewModel(IDialogService dialogService)
        {
            AllWords.Clear();
            _dialogService = dialogService;
            SingleWords = new ObservableCollection<BookWordModel>();
            Phrases = new ObservableCollection<BookWordModel>();
            AddCommand = new DelegateCommand(OnAddWord);
            CharacterCommand = new DelegateCommand<object>(OnCharacterClick);
            CancelExerciseCommand = new DelegateCommand(CancelExercise);
            StartExerciseCommand = new DelegateCommand(StartExercise);
            PrintCommand = new DelegateCommand(PrintEvent);
            //PrintCommand = new DelegateCommand(async () => await OnCaiJi());//临时使用
            LoadCatalogBooks(2);

        }

        

        /// <summary>
        /// 打印已选择词语
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void PrintEvent()
        {

            if (AllWords.Where(s => s.IsSelected == true).Count() > 0)
            {


                //给表单传值 
                DialogParameters param = new DialogParameters();
                param.Add("objs", AllWords.Where(s => s.IsSelected == true).ToList());//传递参数

                _dialogService.ShowDialog("FmPrint", param, arg =>
                {
                    if (arg.Result == ButtonResult.OK)
                    {
                        //var result = arg.Parameters.GetValues<string>("name");//返回参数
                    }
                });
            }
            else
            {
                HandyControl.Controls.Growl.Warning("请选择字词", "InfoMessage");
                return;
            }
        }

        private void OnCharacterClick(object param)
        {
            var selectedWord = param as BookWordModel;
            // 切换选中状态
            selectedWord.IsSelected = !selectedWord.IsSelected;

            // 同步到 AllWords 中
            var match = AllWords.FirstOrDefault(w =>w.Character == selectedWord.Character &&w.CatalogId == selectedWord.CatalogId);

            if (match != null)
            {
                match.IsSelected = selectedWord.IsSelected;
            }

            

            if (selectedWord != null && selectedWord.Character.Length == 1)
            {
                //定义了 _isCheckingSingleWord 和 _isCheckingPhrase，它们本来是防止 setter 再入用的。
                //你可以在加载时 手动控制这两个标志位：
                _isCheckingSingleWord = true;
                // 更新全选框状态
                IsAllWordsChecked = SingleWords.All(word => word.IsSelected && word.CatalogId==selectedWord.CatalogId && word.WordType==10);
                _isCheckingSingleWord = false;
            }
            else //词语选择处理
            {

                _isCheckingPhrase = true;
                // 更新全选框状态
                IsAllPhraseChecked = Phrases.All(word => word.IsSelected && word.CatalogId == selectedWord.CatalogId && word.WordType==20);
                _isCheckingPhrase = false;
            }
            //最后更新章节右上标
            var cats = Catalogs.FirstOrDefault(s => s.Id == selectedWord.CatalogId);
            if(cats!=null)
            {
                cats.F_Count = AllWords.Where(s => s.CatalogId == selectedWord.CatalogId && s.IsSelected == true).Count();
            }
            Console.WriteLine($"**************AllWord={AllWords.Count},选中数={AllWords.Where(s => s.IsSelected).Count()}");
        }

        // 命令处理逻辑
        private void OnAddWord()
        {

            if (SelectedCatalog != null && SelectedCatalog.F_Cls == 10)
            {

                Console.WriteLine($"FmWord bookId={SelectedCatalog.F_BooksId} cataId={SelectedCatalog.Id}");
                //给表单传值 
                DialogParameters param = new DialogParameters();
                param.Add("bookId", SelectedCatalog.F_BooksId);//传递参数
                param.Add("cataId", SelectedCatalog.Id);//传递参数
                _dialogService.ShowDialog("FmWord", param, arg =>
                {
                    if (arg.Result == ButtonResult.OK)
                    {
                        LoadWord(SelectedCatalog.F_BooksId, SelectedCatalog.Id);
                        LoadWords(SelectedCatalog.F_BooksId, SelectedCatalog.Id);
                        //var result = arg.Parameters.GetValues<string>("name");//返回参数
                    }
                });
            }
            else
            {
                HandyControl.Controls.Growl.Warning("请选择课程目录", "InfoMessage");
                return;
            }
            //SingleWords.Add(new WordModel { Character = "新", Pinyin = "xīn", ShowPinyin = true });


        }




        private void CancelExercise()
        {

        }

        private void StartExercise()
        {
            // 执行开始练习逻辑
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            // 从导航参数中获取工单编号
            var bookId = 2;// navigationContext.Parameters.GetValue<int>("bookId");

            if (bookId > 0)
            {
                Console.WriteLine("图书ID=" + bookId);
                LoadCatalogBooks(bookId);
            }
        }


        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            // 可以在此处清理或保存数据
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            // 如果页面需要重用，则返回 true
            return true;
        }


        /// <summary>
        /// 加载左侧图书目录
        /// </summary>
        /// <param name="bookId"></param>
        private void LoadCatalogBooks(int bookId)
        {
            var repo = RF.ResolveInstance<Base_CatalogBookRepository>();
            Catalogs = repo.GetAll().Where(e => e.F_BooksId == bookId).ToList();
        }
        /// <summary>
        /// 加载右侧汉字
        /// </summary>
        /// <param name="bookId"></param>
        /// <param name="catalogId"></param>
        private void LoadWord(int bookId, int catalogId)
        {
            //Console.WriteLine($"加载课本 汉字={bookId}章节={catalogId}");
            var repo = RF.ResolveInstance<YuWen_BookWordRepository>();
            var lst = repo.GetsBy(bookId, catalogId);
            
            
            foreach (var item in lst)
            {

                var obj = new BookWordModel();
                obj.Character = item.F_Name;
                if (!string.IsNullOrEmpty(item.F_PinYin) && item.F_PinYin.Contains('|'))
                    obj.Pinyin = item.F_PinYin.Split('|')[0];
                else
                    obj.Pinyin = item.F_PinYin;
                obj.ShowPinyin = item.ShowPinyin;
                obj.IsSelected = false;
                obj.WordId= item.F_WordId;
                obj.CatalogId = catalogId;
                obj.WordType = 10;

                var bit = AllWords.FirstOrDefault(s => s.Character == obj.Character && s.CatalogId == catalogId);
                if (bit == null)
                {
                    AllWords.Add(obj);                    
                }
                Console.WriteLine($"{obj.Character}={obj.IsSelected}");
            }
            SingleWords.Clear();
            var list = AllWords.Where(s => s.CatalogId == catalogId && s.WordType == 10);
            foreach (var item in list)
            {
                Console.WriteLine($"AllWords=>{item.Character}={item.IsSelected}");
            }
            SingleWords = new ObservableCollection<BookWordModel>(list);
            foreach (var item in SingleWords)
            {
                Console.WriteLine($"SingleWords=>{item.Character}={item.IsSelected}");
            }
            //定义了 _isCheckingSingleWord 和 _isCheckingPhrase，它们本来是防止 setter 再入用的。
            //你可以在加载时 手动控制这两个标志位：
            _isCheckingSingleWord = true;
            IsAllWordsChecked = SingleWords.All(word => word.IsSelected);//这里要补充切换章节更新全选框状态
            _isCheckingSingleWord = false;
        }
        /// <summary>
        /// 加载右侧词语
        /// </summary>
        /// <param name="bookId"></param>
        /// <param name="catalogId"></param>
        private void LoadWords(int bookId, int catalogId)
        {
            //Console.WriteLine($"加载课本 词语={bookId}章节={catalogId}");
            var repo = RF.ResolveInstance<YuWen_BookWordsRepository>();
            var lst = repo.GetsBy(bookId, catalogId);
            
            foreach (var item in lst)
            {
                //Console.WriteLine($"{item.F_Name},{item.F_PinYin},{item.ShowPinyin}");

                var obj = new BookWordModel();
                obj.Character = item.F_Name;
                if (!string.IsNullOrEmpty(item.F_PinYin) && item.F_PinYin.Contains('|'))
                    obj.Pinyin = item.F_PinYin.Split('|')[0];
                else
                    obj.Pinyin = item.F_PinYin;
                obj.ShowPinyin = item.ShowPinyin;
                obj.IsSelected = false;
                obj.WordId = item.F_WordsId;
                obj.CatalogId = catalogId;
                obj.WordType = 20;

                var bit = AllWords.FirstOrDefault(s=>s.Character==obj.Character && s.CatalogId == catalogId);
                if (bit == null)
                {
                    AllWords.Add(obj);
                    //Console.WriteLine($"{obj.Character},{obj.Pinyin},{obj.ShowPinyin},{obj.IsSelected}");
                }
                    
                
                    
            }
            Phrases.Clear();
            var list = AllWords.Where(s => s.CatalogId == catalogId && s.WordType == 20);
            foreach (var item in list)
            {
                Console.WriteLine($"AllWords=>{item.Character}={item.IsSelected}");
            }
            Phrases = new ObservableCollection<BookWordModel>(list);
            foreach (var item in Phrases)
            {
                Console.WriteLine($"Phrases=>{item.Character}={item.IsSelected}");
            }
            _isCheckingPhrase = true;
            IsAllPhraseChecked = Phrases.All(word => word.IsSelected);//这里要补充切换章节更新全选框状态
            _isCheckingPhrase = false;
            
            //Console.WriteLine("===============================");
            //Console.WriteLine($"AllWord={AllWords.Count},选中数={AllWords.Where(s => s.IsSelected).Count()}");
            //Console.WriteLine($"{catalogId}章节字词选中总数={AllWords.Where(s => s.CatalogId == catalogId && s.IsSelected == true).Count()}");
        }
    }


}


